<template>
	<div>
		<el-menu :default-active="activeIndex" class="el-menu-demo">
			<div class="head-nav-one">
				<el-menu-item index="1" @click="gohone">购物星球官网</el-menu-item>
		        <el-menu-item index="2" @click="classfif">商品分类</el-menu-item>
		        <el-menu-item index="3" @click="mycars">我的购物车</el-menu-item>
			</div>
			<div class="head-nav-two">
				<el-menu-item index="4" v-if="isLoggedIn">
					<el-dropdown>
					  <span class="el-dropdown-link">
					    {{username}}<i class="el-icon-arrow-down el-icon--right"></i>
					  </span>
					  <el-dropdown-menu slot="dropdown">
					    <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
					  </el-dropdown-menu>
					</el-dropdown>
				</el-menu-item>
				<el-menu-item index="5" @click="inlogin">{{ loginText }}</el-menu-item>
			</div>
		</el-menu>
	</div>
</template>

<script>
	export default{
		data() {
			return{
				 activeIndex: '1',
				 username: '未登录',
				 isLoggedIn: false
			}
		},
		created() {
		    this.checkLoginStatus();
		},
		computed: {
			loginText() {
				return this.isLoggedIn ? '切换账号' : '登录/注册';
			}
		},
		methods:{
			inlogin(){
				this.$router.push('/login')
			},
			logout(){
				// 清除本地存储的用户信息
				localStorage.removeItem("user");
				// 更新登录状态
				this.isLoggedIn = false;
				// 更新用户名显示
				this.username = '未登录';
				// 可以添加跳转到登录页或其他操作
				this.$router.push('/login');
				// 提示用户已退出
				this.$message.success('已成功退出登录');
			},
			// 商品分类
			classfif(){
				this.$router.push("/classifigoods")
			},
			checkLoginStatus() {
			    // 检查用户登录状态
			    const userData = JSON.parse(localStorage.getItem("user"));
			    if(userData && userData.username) {
			    	this.isLoggedIn = true;
			    	this.username = userData.username;
			    } else {
			    	this.isLoggedIn = false;
			    	this.username = '未登录';
			    }
			},
			mycars(){
				this.$router.push("/cart")
			},
			gohone(){
				this.$router.push("/")
			}
			
		}
	}
</script>

<style scoped>
	.el-menu-demo{
		display: flex;
	}
	.head-nav-one{
		display: flex;
		gap: 10px;
		margin-left: 20px;
	}
	.head-nav-two{
		display: flex;
		margin-left: auto;
		margin-right: 20px;
	}
	.el-dropdown-link {
		cursor: pointer;
		color: inherit;
	}
</style>